import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/comic_dayqd_model.dart';
import '../models/comic_user_model.dart';
import '../utils/http_helper.dart';
import '../utils/user_manager.dart';

/// -------------------- 状态类 --------------------
class DailyCheckInState {
  final int consecutiveDays;
  final int currentCoins;
  final List<ComicDayqdModel> rewards;
  final bool isLoading;
  final UserData? userInfo; // 添加用户信息

  DailyCheckInState({
    this.consecutiveDays = 0,
    this.currentCoins = 0,
    this.rewards = const [],
    this.isLoading = false,
    this.userInfo,
  });

  DailyCheckInState copyWith({
    int? consecutiveDays,
    int? currentCoins,
    List<ComicDayqdModel>? rewards,
    bool? isLoading,
    UserData? userInfo,
  }) {
    return DailyCheckInState(
      consecutiveDays: consecutiveDays ?? this.consecutiveDays,
      currentCoins: currentCoins ?? this.currentCoins,
      rewards: rewards ?? this.rewards,
      isLoading: isLoading ?? this.isLoading,
      userInfo: userInfo ?? this.userInfo,
    );
  }
}

/// -------------------- Notifier --------------------
class DailyCheckInNotifier extends StateNotifier<DailyCheckInState> {
  DailyCheckInNotifier() : super(DailyCheckInState()) {
    // 构造时自动加载数据
    loadData();
  }

  /// 加载签到任务和已签到状态
  Future<void> loadData({bool showLoading = true}) async {
    if (showLoading) {
      state = state.copyWith(isLoading: true);
    }

    // 获取用户信息（用于显示真实余额）
    UserData? userInfo;
    try {
      userInfo = await UserManager.getUserInfo();
    } catch (e) {
      // 获取用户信息失败，继续执行
    }
    try {
      // 1. 获取签到任务
      final taskResponse = await HttpUtil().getModel<List<ComicDayqdModel>>(
        'Comic/GetTaskSettingList',
        fromJson: (json) {
          return (json as List)
              .map((item) => ComicDayqdModel.fromJson(item))
              .toList();
        },
      );

      List<ComicDayqdModel> rewards = taskResponse?.result ?? [];

      // 2. 获取已签到数据
      final signedResponse = await HttpUtil().getModel<List<ComicDayqdModel>>(
        'Comic/GetMemberTaskList',
        fromJson: (json) {
          return (json as List)
              .map((item) => ComicDayqdModel.fromJson(item))
              .toList();
        },
      );

      List<ComicDayqdModel> signedList = signedResponse?.result ?? [];

      // 3. 更新 rewards 的 isChecked 状态
      for (var reward in rewards) {
        // 如果用户签到了N天，那么前N天都应该显示为已签到
        reward.isChecked = reward.day! <= signedList.length;
      }

      // 4. 计算连续签到天数，使用用户真实余额
      int consecutiveDays = signedList.length; // 签到记录数量就是连续签到天数
      double realBalance = userInfo?.balance ?? 0; // 使用用户真实余额

      state = state.copyWith(
        rewards: rewards,
        consecutiveDays: consecutiveDays,
        currentCoins: realBalance.toInt(), // 使用真实余额
        userInfo: userInfo, // 保存用户信息
        isLoading: false,
      );
    } catch (error) {
      state = state.copyWith(
        rewards: [],
        currentCoins: 0,
        consecutiveDays: 0,
        userInfo: null,
        isLoading: false,
      );
    }
  }

  /// 刷新数据
  Future<void> refresh({bool showLoading = false}) async {
    await loadData(showLoading: showLoading);
  }

  /// 签到奖励 - 移除假的本地状态更新逻辑
  void claimReward(ComicDayqdModel reward) {
    // 移除了假的本地状态更新逻辑
    // 如需实现真实签到功能，应该：
    // 1. 调用签到API
    // 2. 重新调用 loadData() 获取最新状态
  }
}

final dailyCheckInProvider =
    StateNotifierProvider.autoDispose<DailyCheckInNotifier, DailyCheckInState>(
  (ref) => DailyCheckInNotifier(),
);

/// -------------------- 页面 --------------------
class DailyCheckInScreen extends ConsumerWidget {
  const DailyCheckInScreen({super.key});

  // 颜色配置
  Color get primaryColor => const Color(0xFFE6C068); // 金色
  Color get secondaryColor => const Color(0xFF724CF9); // 紫色
  Color get cardBgColor => const Color(0xFF2A1F3D); // 卡片背景
  Color get textPrimary => Colors.white;
  Color get textSecondary => Colors.white70;
  Color get textTertiary => Colors.white54;
  Color get checkedColor => const Color(0xFF9C7C38); // 已签到
  Color get todayColor => const Color(0xFF9C7C38).withOpacity(0.2); // 今日可签到
  Color get futureColor => const Color(0xFF3D2F4F); // 未来未签到

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(dailyCheckInProvider);
    final notifier = ref.read(dailyCheckInProvider.notifier);

    // 移除了自动加载逻辑，防止无限循环
    // 数据加载现在在 StateNotifier 构造时自动进行

    if (state.isLoading) {
      return const Scaffold(
        backgroundColor: Color(0xFF211839),
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (state.rewards.isEmpty) {
      return const Scaffold(
        backgroundColor: Color(0xFF211839),
        body: Center(
          child: Text(
            'No comics',
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
        ),
      );
    }

    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// 顶部栏
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  IconButton(
                    icon: Icon(Icons.arrow_back, color: textPrimary, size: 20),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '${state.currentCoins}',
                    style: TextStyle(
                      color: primaryColor,
                      fontSize: 36,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    'My Account',
                    style: TextStyle(
                      color: textSecondary,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 12),

            /// 7天签到卡片
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(
                color: cardBgColor,
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 15,
                    offset: const Offset(0, 8),
                  ),
                ],
              ),
              child: Column(
                children: [
                  /// 标题栏
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 12,
                    ),
                    decoration: BoxDecoration(
                      color: secondaryColor,
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(20),
                        topRight: Radius.circular(20),
                      ),
                    ),
                    child: const Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '7 Day',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          'Check in rewards',
                          style: TextStyle(
                            color: Colors.white70,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),

                  /// 连续签到提示
                  Padding(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: RichText(
                      text: TextSpan(
                        text: 'Check in for ',
                        style: TextStyle(color: textTertiary, fontSize: 12),
                        children: [
                          TextSpan(
                            text: '${state.consecutiveDays}',
                            style: TextStyle(
                              color: primaryColor,
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          TextSpan(
                            text: ' consecutive days',
                            style: TextStyle(color: textTertiary, fontSize: 12),
                          ),
                        ],
                      ),
                    ),
                  ),

                  /// 奖励网格
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    child: Column(
                      children: [
                        Row(
                          children: state.rewards
                              .where((r) => r.day! <= 4)
                              .map((r) => Expanded(
                                    child: _buildRewardItem(
                                        context, r, state, notifier),
                                  ))
                              .toList(),
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: state.rewards
                              .where((r) => r.day! > 4)
                              .map((r) => Expanded(
                                    child: _buildRewardItem(
                                        context, r, state, notifier),
                                  ))
                              .toList(),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 16),

                  /// Draw down 按钮
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Column(
                      children: [
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: () => _handleDrawDown(context, notifier),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: primaryColor,
                              foregroundColor: const Color(0xFF1A202C),
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(25),
                              ),
                              elevation: 0,
                            ),
                            child: const Text(
                              'Draw down',
                              style: TextStyle(
                                  fontSize: 14, fontWeight: FontWeight.w600),
                            ),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          'Get more free coins for continuously check-in',
                          style: TextStyle(color: textTertiary, fontSize: 10),
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 16),
                ],
              ),
            ),

            const Spacer(),
          ],
        ),
      ),
    );
  }

  /// 奖励Item
  Widget _buildRewardItem(BuildContext context, ComicDayqdModel reward,
      DailyCheckInState state, DailyCheckInNotifier notifier) {
    bool isToday = reward.day == state.consecutiveDays + 1;
    bool canClaim = isToday && !reward.isChecked;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 4),
      decoration: BoxDecoration(
        color: reward.isChecked
            ? checkedColor
            : (isToday ? todayColor : futureColor),
        borderRadius: BorderRadius.circular(12),
        border: isToday && !reward.isChecked
            ? Border.all(color: primaryColor, width: 2)
            : null,
      ),
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
      child: Column(
        children: [
          Container(
            width: 24,
            height: 24,
            decoration: BoxDecoration(
              color: reward.isChecked
                  ? Colors.white.withOpacity(0.2)
                  : primaryColor,
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.diamond, color: Colors.white, size: 16),
          ),
          const SizedBox(height: 4),
          Text(
            'DAY ${reward.day}',
            style: TextStyle(
              color: reward.isChecked ? Colors.white : textSecondary,
              fontSize: 10,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: 2),
          Text(
            'x${reward.reward}',
            style: TextStyle(
              color: reward.isChecked ? Colors.white : primaryColor,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  /// Draw down 弹窗
  Future<void> _handleDrawDown(
      BuildContext context, DailyCheckInNotifier notifier) async {
    final response = await HttpUtil().postJson(
      'Comic/AddMemberTask',
    );

    // 判断status是否等于200
    if (response != null && response['status'] == 200) {
      // 静默刷新页面数据，不显示全屏加载
      await notifier.loadData(showLoading: false);

      // 请求成功，显示成功弹窗
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          backgroundColor: cardBgColor,
          title: Text('Draw Down', style: TextStyle(color: textPrimary)),
          content: Text(
            'Congratulations! You got bonus coins from draw down!',
            style: TextStyle(color: textSecondary),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('OK', style: TextStyle(color: primaryColor)),
            ),
          ],
        ),
      );
    } else {
      // 请求失败，显示错误提示
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          backgroundColor: cardBgColor,
          title: Text('Error', style: TextStyle(color: textPrimary)),
          content: Text(
            'Failed to complete draw down. Please try again.',
            style: TextStyle(color: textSecondary),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('OK', style: TextStyle(color: primaryColor)),
            ),
          ],
        ),
      );
    }
  }
}
